//
//  MBHTTPNetworking.m
//  Meboo
//
//  Created by kyo on 2023/10/7.
//

#import "MBHTTPNetworking.h"
#import <AFHTTPSessionManager.h>
#import "KLLoginViewController.h"


static  MBHTTPNetworking  *wsNetworking = nil;
static  AFHTTPSessionManager *manager  = nil;


@interface MBHTTPNetworking (){
    
    NSString  *boundary;
    NSString  *fileParam;
    NSString  *baseUrl;
    NSString  *fileName;
}

@property (nonatomic, strong) NSMutableDictionary *errorDictM;
@property (nonatomic, copy) NSString *errorStr;
@end


@implementation MBHTTPNetworking


+ (MBHTTPNetworking *)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        wsNetworking = [[MBHTTPNetworking alloc]init];
        manager =  [AFHTTPSessionManager manager];
        
        NSString *errorPath = [[NSBundle mainBundle] pathForResource:@"error.plist" ofType:nil];
        NSArray<NSDictionary *>*errorArray = [NSArray arrayWithContentsOfFile:errorPath];
        wsNetworking.errorDictM = [NSMutableDictionary dictionary];
        [errorArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [wsNetworking.errorDictM setValue:obj[@"result"] forKey:obj[@"num"]];
        }];
    });
    
    return wsNetworking;
    
    
    
}


#pragma mark - 网络监测(在什么网络状态)
- (void)networkStatusUnknown:(Unknown)unknown
                   reachable:(Reachable)reachable
            reachableViaWWAN:(ReachableViaWWAN)reachableViaWWAN
            reachableViaWiFi:(ReachableViaWiFi)reachableViaWiFi;
{
    // 创建网络监测者
    AFNetworkReachabilityManager *reachabilitymanager = [AFNetworkReachabilityManager sharedManager];
    
    [reachabilitymanager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 监测到不同网络的情况
        switch (status)
        {
            case AFNetworkReachabilityStatusUnknown:
                unknown();
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                reachable();
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                reachableViaWWAN();
                
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                reachableViaWiFi();
                break;
                
            default:
                break;
        }
    }] ;
    
    // 开始监听网络状况
    [reachabilitymanager startMonitoring];
}


#pragma mark - https TLS验证
- (AFSecurityPolicy *)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"hgcang" ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    NSSet *certSet = [[NSSet alloc]initWithObjects:certData, nil];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    securityPolicy.pinnedCertificates = certSet;
    
    return securityPolicy;
}



#pragma mark - 无需认证请求(有加载菊花)----删除菊花
- (void)WSAFNoOAuthUrlString:(NSString * _Nullable)urlString
                      method:(NSString * _Nullable)method
                  parameters:(id _Nullable)parameters
                     success:(Success)success
                     failure:(Failure)failure
{
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    //设置允许接收返回数据类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"charset=UTF-8", @"application/x-www-form-urlencoded",@"multipart/form-data", @"text/plain", nil];
    manager.requestSerializer.timeoutInterval = 45;  //设置超时时间
    //    if ([MBUserAccount defaultAccount].token != nil) {
    //        [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@",[MBUserAccount defaultAccount].token] forHTTPHeaderField:@"token"];
    //    }
    //
    //    [manager.requestSerializer setValue:[self getTimeNow] forHTTPHeaderField:@"timestamp"];
    //    [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"channel"];
    //    [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"appsFlyerUID"];
    //    [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"appCode"];
    //    [manager.requestSerializer setValue:@"com.meboo.test.ios" forHTTPHeaderField:@"applicationID"];
    //    [manager.requestSerializer setValue:@"1.0.0" forHTTPHeaderField:@"appVersion"];
    //    [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"token"];
    //    [manager.requestSerializer setValue:@"1.0.0" forHTTPHeaderField:@"appVersionName"];
    //    [manager.requestSerializer setValue:@"2" forHTTPHeaderField:@"appSource"];
    
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:[self getTimeNow] forKey:@"timestamp"];
    [params setObject:@"1" forKey:@"channel"];
    [params setObject:@"" forKey:@"appsFlyerUID"];
    [params setObject:@"" forKey:@"appCode"];
    [params setObject:@"com.meboo.test.ios" forKey:@"applicationID"];
    [params setObject:@"1.0.0" forKey:@"appVersion"];
    [params setObject:@"" forKey:@"token"];
    [params setObject:@"1.0.0" forKey:@"appVersionName"];
    [params setObject:@"2" forKey:@"appSource"];
    
//    [manager.requestSerializer setValue:@"{\"appVersionName\":\"1.0.0\",\"appVersion\":\"1.0.0\",\"channel\":\"1\",\"applicationID\":\"com.meboo.test.ios\",\"appsFlyerUID\":\"\",\"appCode\":\"\",\"token\":\"\",\"timestamp\":\"1696993380000\",\"appSource\":\"2\"}" forHTTPHeaderField:@"basicParams"];
    
    //guestId 是根据两个版本来确认的一个特殊标识符
    NSString *from = @"2";
    if ([MBUserAccount defaultAccount].isNewHome == 2) {
        from = @"1";
    }
    NSString *headerStr = [NSString stringWithFormat:@"{\"timestamp\":\"%@\",\"channel\":\"1\",\"appsFlyerUID\":\"\",\"appCode\":\"sparksy_ios\",\"applicationID\":\"com.meboo.ios\",\"appVersion\":\"1\",\"token\":\"%@\",\"appVersionName\":\"%@\",\"appSource\":\"2\",\"from\":\"%@\"}",[self getTimeNow],[MBUserAccount defaultAccount].token,[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"],from];    [manager.requestSerializer setValue:headerStr forHTTPHeaderField:@"basicParams"];
    NSString *url;
    
    url = [NSString stringWithFormat:@"%@%@",BaseAPI,urlString];
    NSLog(@"完整链接：%@",url);
    
    if ([urlString containsString:@"https://gcdsdk.appsflyer"] || [urlString containsString:@"https://sandbox.itunes"]) {
        url = urlString;
    }
    
    //    [SVProgressHUD showWithStatus:@"加载中"];
    
    if ([method isEqualToString:@"POST"]) {
        [manager POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dic;
            // 请求成功，解析数据
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                dic = responseObject;
            }else{
                dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            }
            //            [SVProgressHUD dismiss];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            NSInteger code = [dic[@"code"] integerValue];
            if (code == 700) {
                [MBUserAccount deleteDoc];
                AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
                //token失效重新登陆
                BaseNavViewController *nav = [[BaseNavViewController alloc] initWithRootViewController:[[KLLoginViewController alloc]init]];
                appDelegate.window.rootViewController = nav;
            } else {
                success(dic);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //            [SVProgressHUD showInfoWithStatus:RVString(@"networkError")];
            failure(error);
        }];
    } else if ([method isEqualToString:@"GET"]) {
        [manager GET:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic;
            // 请求成功，解析数据
            if ([responseObject isKindOfClass:[NSDictionary class]] || [responseObject isKindOfClass:[NSMutableDictionary class]]) {
                dic = responseObject;
            }else{
                dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            }
            
            //            [SVProgressHUD dismiss];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            //            [SVProgressHUD showInfoWithStatus:RVString(@"networkError")];
            //            [SVProgressHUD showInfoWithStatus:[error localizedDescription]];
            NSLog(@"请求失败：%@", [error localizedDescription]);
            failure(error);
        }];
    }else if ([method isEqualToString:@"PATCH"]){
        [manager PATCH:url parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 请求成功，解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            
            //            [SVProgressHUD dismiss];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //            [SVProgressHUD showInfoWithStatus:[error localizedDescription]];
            NSLog(@"请求失败：%@", [error localizedDescription]);
            failure(error);
        }];
    }else if ([method isEqualToString:@"PUT"]){
        [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
        [manager PUT:url parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dic;
            // 请求成功，解析数据
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                dic = responseObject;
            }else{
                dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            }
            //            [SVProgressHUD dismiss];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //            [SVProgressHUD showInfoWithStatus:RVString(@"networkError")];
            failure(error);
        }];
    }else{
        [manager DELETE:url parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 请求成功，解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            
            //            [SVProgressHUD dismiss];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //            [SVProgressHUD showInfoWithStatus:[error localizedDescription]];
            NSLog(@"请求失败：%@", [error localizedDescription]);
            failure(error);
        }];
    }
    
    
    
}


#pragma mark - 无需认证请求(有加载菊花)-----加上菊花
- (void)WSAFNHudUrlString:(NSString * _Nullable)urlString
                   method:(NSString * _Nullable)method
               parameters:(id _Nullable)parameters
                  success:(Success)success
                  failure:(Failure)failure
{
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    //设置允许接收返回数据类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"charset=UTF-8", @"application/x-www-form-urlencoded", @"text/plain", nil];
    manager.requestSerializer.timeoutInterval = 20;  //设置超时时间
    if ([MBUserAccount defaultAccount].token != nil) {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@",[MBUserAccount defaultAccount].token] forHTTPHeaderField:@"token"];
    }
    
    NSString *url;
    url = [NSString stringWithFormat:@"%@%@",BaseAPI,urlString];
    NSLog(@"完整链接：%@",url);
    
    //    [SVProgressHUD showWithStatus:RVString(@"isUsing1")];
    
    if ([method isEqualToString:@"POST"]) {
        [manager POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dic;
            // 请求成功，解析数据
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                dic = responseObject;
            }else{
                dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            }
            //            [SVProgressHUD dismiss];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //            [SVProgressHUD dismiss];
            failure(error);
        }];
    } else if ([method isEqualToString:@"GET"]) {
        NSArray *arr = [parameters allKeys];
        // 遍历arr 取出对应的key以及key对应的value
        for (NSInteger i = 0; i < arr.count; i++) {
            url = [NSString stringWithFormat:@"%@?%@=%@",url,arr[i],[parameters objectForKey:arr[i]]];
        }
        url = [url stringByReplacingOccurrencesOfString:@"#" withString:@"%23"];
        url = [url stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
        [manager GET:url parameters:nil headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic;
            // 请求成功，解析数据
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                dic = responseObject;
            }else{
                dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            }
            
            //            [SVProgressHUD dismiss];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            //            [SVProgressHUD dismiss];
            //            [SVProgressHUD showInfoWithStatus:[error localizedDescription]];
            NSLog(@"请求失败：%@", [error localizedDescription]);
            failure(error);
        }];
    }else if ([method isEqualToString:@"PATCH"]){
        [manager PATCH:url parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 请求成功，解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            
            //            [SVProgressHUD dismiss];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //            [SVProgressHUD showInfoWithStatus:[error localizedDescription]];
            NSLog(@"请求失败：%@", [error localizedDescription]);
            failure(error);
        }];
    }else if ([method isEqualToString:@"PUT"]){
        [manager PUT:url parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 请求成功，解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            
            //            [SVProgressHUD dismiss];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            
            //            [SVProgressHUD showInfoWithStatus:[error localizedDescription]];
            NSLog(@"请求失败：%@", [error localizedDescription]);
            failure(error);
        }];
    }else{
        [manager DELETE:url parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 请求成功，解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            
            //            [SVProgressHUD dismiss];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //            [SVProgressHUD showInfoWithStatus:[error localizedDescription]];
            NSLog(@"请求失败：%@", [error localizedDescription]);
            failure(error);
        }];
    }
    
}



//#pragma mark - 无需认证请求(无加载菊花)
- (void)WSAFNoOAuthNoUrlString:(NSString * _Nullable)urlString
                        method:(NSString * _Nullable)method
                    parameters:(id _Nullable)parameters
                       success:(Success)success
                       failure:(Failure)failure
{
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置允许接收返回数据类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"charset=UTF-8", @"application/x-www-form-urlencoded", @"text/plain", nil];
    manager.requestSerializer.timeoutInterval = 45;  //设置超时时间
    
    NSString *url = [NSString stringWithFormat:@"%@%@",BaseAPI,urlString];
    NSLog(@"完整链接：%@",url);
    
    if ([method isEqualToString:@"POST"]) {
        [manager POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 请求成功，解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"请求失败：%@", [error localizedDescription]);
            failure(error);
        }];
    }else if ([method isEqualToString:@"PUT"]){
        [manager PUT:url parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 请求成功，解析数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            
            NSLog(@"请求成功，JSON解析后：%@", dic);
            success(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"请求失败：%@", [error localizedDescription]);
            failure(error);
        }];
    }
    
}

#pragma mark - 发送后台统计请求
- (void)WSAFNoOAuthIdfaWithmethod:(NSString * _Nullable)method
                       parameters:(id _Nullable)parameters
                          success:(Success)success
                          failure:(Failure)failure
{
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置允许接收返回数据类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"charset=UTF-8", @"application/x-www-form-urlencoded", @"text/plain", nil];
    manager.requestSerializer.timeoutInterval = 45;  //设置超时时间
    
    NSString *url = [NSString stringWithFormat:@"%@",@"http://adx.borui-ad.com/interface/sijicaifu/gain"];
    
    [manager POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        NSLog(@"请求成功，JSON解析后：%@", dic);
        success(dic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"请求失败：%@", [error localizedDescription]);
        failure(error);
    }];
    
}

- (void)upheaderImageWithParms:(NSDictionary * _Nonnull )parms
                     withImage:(UIImage * _Nonnull)image
               withtargetWidth:(CGFloat )width
                 withUrlString:(NSString * _Nonnull)urlString
              withSuccessBlock:(Success)successBlock
               withFailurBlock:(Failure)failureBlock{
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    //设置允许接收返回数据类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"charset=UTF-8", @"application/x-www-form-urlencoded",@"multipart/form-data", @"text/plain", nil];
    manager.requestSerializer.timeoutInterval = 45;  //设置超时时间
    if ([MBUserAccount defaultAccount].token != nil) {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@",[MBUserAccount defaultAccount].token] forHTTPHeaderField:@"token"];
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@",BaseAPI,urlString];
    NSLog(@"完整链接：%@",url);
    
    //    [SVProgressHUD showWithStatus:@"加载中"];
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    [manager POST:url parameters:parms headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData * imgData;
        if (UIImagePNGRepresentation(image) == nil) {
            imgData = UIImageJPEGRepresentation(image, 1);
        }else{
            imgData = UIImagePNGRepresentation(image);
        }
        [formData appendPartWithFileData:imgData name:@"file" fileName:@"image.png" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic;
        // 请求成功，解析数据
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            dic = responseObject;
        }else{
            dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        }
        //            [SVProgressHUD dismiss];
        
        NSLog(@"请求成功，JSON解析后：%@", dic);
        successBlock(dic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //        [SVProgressHUD showInfoWithStatus:RVString(@"networkError")];
        failureBlock(error);
    }];
    
    
    //
    //    [manager POST:url parameters:parms headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    //
    //            //图片需要压缩就执行这个方法, 下面三个image替换成resizedImage
    ////            UIImage *  resizedImage =  [UIImage IMGCompressed:image targetWidth:width];
    //
    //            NSData * imgData;
    //            if (UIImagePNGRepresentation(image) == nil) {
    //                imgData = UIImageJPEGRepresentation(image, 1);
    //            }else{
    //                imgData = UIImagePNGRepresentation(image);
    //            }
    //            [formData appendPartWithFileData:imgData name:@"file" fileName:@"image.png" mimeType:@"image/png"];
    //
    //        } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
    //
    //            // 请求成功，解析数据
    //            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    //
    //            if ([[dic allKeys] containsObject:@"code"]) {
    //                if ([dic[@"code"] compare:@1] == NSOrderedSame) {
    //                    [SVProgressHUD dismiss];
    //                }
    //            }
    //
    //            successBlock(dic);
    //
    //        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //
    //            NSHTTPURLResponse *errorResponse = error.userInfo[@"com.alamofire.serialization.response.error.response"];
    //            NSString *authenticate = errorResponse.allHeaderFields[@"Www-Authenticate"];
    //
    //            if (errorResponse.statusCode == 401) {
    //
    //
    //                //刷新OAuth认证
    //                NSString *refreshUrl = [NSString stringWithFormat:@"%@%@",BaseAPI,@"/oauth/token"];
    //                NSDictionary *parmas = @{@"client_id":@"iphone_client_credentials",
    //                                         @"client_secret":@"spring_security_oauth2.0_iphone_1a2w3e4r",
    //                                         @"grant_type":@"refresh_token",
    //                                         @"refresh_token":[CommonUtils getInfoObject:vRefresh_token]};
    //
    //                [manager POST:refreshUrl parameters:parmas progress:^(NSProgress * _Nonnull uploadProgress) {
    //
    //                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //
    //                    // 请求成功，解析数据
    //                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    //
    //                    //重新设置refresh_token过期时间
    //                    NSDate *date = [NSDate date];
    //                    NSTimeInterval interval = [date timeIntervalSince1970];
    //                    NSString *expireTime = [NSString stringWithFormat:@"%f",interval + RefreshTokenTime];
    //
    //                    [CommonUtils setInfoObject:expireTime forKey:vExpireTime];
    //                    [CommonUtils setInfoObject:dic[@"access_token"] forKey:vAccess_token];
    //                    [CommonUtils setInfoObject:dic[@"refresh_token"] forKey:vRefresh_token];
    //
    //                    //重新授权后再请求
    //                    NSMutableDictionary *paramsDic = [[NSMutableDictionary alloc]initWithDictionary:parms];
    //                    [paramsDic setObject:[CommonUtils getInfoObject:vAccess_token] forKey:@"access_token"];
    //
    //                    [manager POST:urlStr parameters:paramsDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    //
    //                        UIImage *  resizedImage =  [UIImage IMGCompressed:image targetWidth:width];
    //
    //                        NSData * imgData;
    //                        if (UIImagePNGRepresentation(resizedImage) == nil) {
    //                            imgData = UIImageJPEGRepresentation(resizedImage, 1);
    //                        }else{
    //                            imgData = UIImagePNGRepresentation(resizedImage);
    //                        }
    //                        [formData appendPartWithFileData:imgData name:@"uploadfile" fileName:@"image.png" mimeType:@"image/png"];
    //
    //                    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //
    //                        // 请求成功，解析数据
    //                        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    //
    //                        if ([dic[@"code"] compare:@1] == NSOrderedSame) {
    //                            [SVProgressHUD dismiss];
    //                        }
    //
    //                        successBlock(dic);
    //
    //                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //
    //                        [SVProgressHUD showInfoWithStatus:[error localizedDescription]];
    //                        NSLog(@"请求失败：%@",[error localizedDescription]);
    //                        failureBlock(error);
    //                    }];
    //
    //                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //
    //
    //                    successBlock(@"其他设备登录");
    //                    [WSHTTPNetworking otherDeriverLoginAlert];
    //                }];
    //
    //
    //            } else if ([authenticate rangeOfString:@"unauthorized"].location != NSNotFound) {  //未授权，重新登录
    //                [WSHTTPNetworking loginBackInAlert];
    //                successBlock(@"重新登录");
    //            } else {
    //                [SVProgressHUD showInfoWithStatus:[error localizedDescription]];
    //                NSLog(@"upheaderImageWithParms：%@", [error localizedDescription]);
    //                failureBlock(error);
    //            }
    //            NSLog(@"upheaderImageWithParms:%@",error.localizedDescription);
    //            failureBlock(error);
    //        }];
    //
    ////    }
}

-(NSString *) getTimeNow{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    return timeSp;
}

//字典转json格式字符串：
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&parseError];
    
    NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return str;
}
@end
